package com.tianlan.blog.controller;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.tianlan.blog.dto.QueryEmployeeAttendance;
import com.tianlan.blog.entity.EmployeeAttendance;
import com.tianlan.blog.service.EmployeeAttendanceService;
import com.tianlan.common.base.PageResult;
import com.tianlan.common.base.Result;
import com.tianlan.common.page.MyPage;
import com.tianlan.common.uplpad.FileUtils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/employee/attendance")
@Api(value = "EmployeeAttendanceController|员工考勤的前端控制器")
public class EmployeeAttendanceController {

	@Autowired
	private EmployeeAttendanceService employeeAttendanceService;

	@Value("${file.uploadImgPath}")
	private String uploadImgPath;

	@Value("${file.uploadPath}")
	private String uploadPath;
	
	/**
	 * 查询所有员工考勤列表
	 */
	@GetMapping("/list")
	// @RequiresRoles({"SYSADMIN","BUSINESS_ADMIN"})
	@RequiresRoles("SYSADMIN")
	@ApiOperation(value = "查询员工考勤列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "ID", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "jobNumber", value = "工号", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "employeeName", value = "员工名称", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "dept", value = "部门", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "startDate", value = "创建时间开始(查询时间内)", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "endDate", value = "创建时间结束(查询时间内)", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "size", value = "每页条数", required = false, dataType = "Integer", paramType = "query"),
			@ApiImplicitParam(name = "current", value = "当前页", required = false, dataType = "Integer", paramType = "query") })
	public PageResult<EmployeeAttendance> list(@ApiIgnore QueryEmployeeAttendance employee,
			@ApiIgnore MyPage<EmployeeAttendance> page) {
		List<EmployeeAttendance> employeeAttendanceList = employeeAttendanceService.selectEmployeeAttendanceList(employee,page);
		page.setRecords(employeeAttendanceList);
		page.setTotal(employeeAttendanceService.selectEmployeeAttendanceCount(employee));
		PageResult<EmployeeAttendance> pageResult = new PageResult<EmployeeAttendance>(page.getTotal(),
				page.getRecords());
		return pageResult;
	}

	/**
	 * 上传excel
	 */
	@PostMapping("/upload/excel")
	@RequiresRoles("SYSADMIN")
	@ApiOperation(value = "上传excel")
	@ResponseBody
	public Result<?> uplpad(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
		// 设置文件大小
		// 你这得到的后缀名是带.（点）的
		if (file.isEmpty()) {
			return new Result<>().error("文件为空");
		}
		// 1.获取原文件名 File.separatorChar
		String fileName = file.getOriginalFilename();
		String suffixName = fileName.substring(fileName.lastIndexOf("."));
		fileName = UUID.randomUUID().toString().replaceAll("-", "") + suffixName; // 新文件名
		File dest = new File(uploadPath + fileName);
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs(); // 判断文件目录是否存在
		}
		try {
			file.transferTo(dest);
			String src = uploadPath + fileName;
			Result<?> insertConut = eximport(src);
			return new Result<>().success("上传成功").put(insertConut);
		} catch (IllegalStateException e) {
			return new Result<>().error("图片保存失败");
		} catch (IOException e) {
			return new Result<>().error("图片保存失败--IO异常");
		}
	}
	
	public Result<?> eximport(String src) {
		ImportParams params = new ImportParams();
		params.setTitleRows(2);
		params.setHeadRows(2);
		List<EmployeeAttendance> list = new ArrayList<>();
		list = ExcelImportUtil.importExcel(new File(src), EmployeeAttendance.class, params);
		List<EmployeeAttendance> insertList = employeeAttendanceService.insertEmployeeAttendanceList(list);
		// List<EmployeeAttendanceExcelVo> list=new ArrayList<>();
		// list = ExcelImportUtil.importExcel(new File(src),
		// EmployeeAttendanceExcelVo.class, params);
		// for (int i = 0; i <list.size() ; i++) {
		// System.out.println(list.get(i).getJobNumber());
		// System.out.println(list.get(i).getEmployeeName());
		// System.out.println(list.get(i).getDept());
		// System.out.println(list.get(i).getStandardWorkHour());
		// System.out.println(list.get(i).getActualWorkHour());
		// System.out.println(list.get(i).getLateNumber());
		// System.out.println(list.get(i).getLateMinute());
		// System.out.println(list.get(i).getLeaveEarlyNumber());
		// System.out.println(list.get(i).getLeaveEarlyMinute());
		// System.out.println(list.get(i).getOvertimeHour());
		// System.out.println(list.get(i).getHolidayOvertimeHour());
		// System.out.println(list.get(i).getAttendanceDay());
		// System.out.println(list.get(i).getBusinessTripDay());
		// System.out.println(list.get(i).getAbsenteeismDay());
		// System.out.println(list.get(i).getAskForLeaveDay());
		// System.out.println(list.get(i).getStandardAdditionalWage());
		// System.out.println(list.get(i).getOvertimeAdditionalWage());
		// System.out.println(list.get(i).getAllowanceAdditionalWage());
		// System.out.println(list.get(i).getLateDeductionWage());
		// System.out.println(list.get(i).getAskForLeaveDeductionWage());
		// System.out.println(list.get(i).getDeductDeductionWage());
		// System.out.println(list.get(i).getRealWage());
		// System.out.println(list.get(i).getRemarks());
		// }
		return new Result<>().success("上传员工数据成功").put(insertList.size());
	}
	
	@PostMapping("/upload/image")
	@RequiresRoles("SYSADMIN")
	@ApiOperation(value = "上传员工图片")
	@ResponseBody
	public Result<?> updateImg(@RequestParam(value = "file") MultipartFile file,@RequestParam(value = "id") Integer id) {
        if (null == id) {
            return new Result<>().error("用户ID不能为空");
        }
		Result<?> isImg = FileUtils.uploadImg(file, uploadImgPath);
		System.out.println(isImg.getCode());
		if(isImg.getCode() != 200){
			return new Result<>().error().put(isImg.getMsg());
		}
		String imgUrl = (String) isImg.getData();
		boolean isUpdateImg = employeeAttendanceService.updateImg(imgUrl, id);
		if(isUpdateImg){
			return new Result<>().success("图片修改成功");
		}else{
			return new Result<>().error("图片修改失败");
		}
	}
	
	/**
	 * 导出
	 *
	 * @param response
	 * @throws IOException
	 */
	@GetMapping("/export")
	@RequiresRoles("SYSADMIN")
	@ResponseBody
	public Result<?> exportExcel(HttpServletResponse response) throws IOException {
		List<EmployeeAttendance> list = employeeAttendanceService.findAllByDelFlag();
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("员工考勤表", "员工"), EmployeeAttendance.class, list);
		response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode("员工考勤汇总" + ".xls","utf-8"));
		response.setContentType("application/x-msdownload");
		response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
		workbook.write(response.getOutputStream());
		return new Result<>().success("成功").put(response);
	}

//	/**
//	 * 导出
//	 *
//	 * @param response
//	 * @throws IOException
//	 */
//	@GetMapping("/export")
//	@RequiresRoles("SYSADMIN")
//	@ResponseBody
//	public void exportExcel(HttpServletResponse response) {
//		List<EmployeeAttendance> list = employeeAttendanceService.findAllByDelFlag();
//		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("员工考勤表", "员工"), EmployeeAttendance.class, list);
////		fos.close(); URLEncoder.encode("员工考勤汇总" + ".xls","utf-8")
//		response.reset();
//		response.setHeader("Content-Disposition","attachment;filename=" +"11.xls" );
//		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//		response.setHeader("Pragma", "no-cache");
//		response.setHeader("Cache-Control", "no-cache");
//		response.setDateHeader("Expires", 0);
//		try {
////			FileOutputStream fos = new FileOutputStream("D://tlblog-tmp//员工考勤表1.xls");
////			workbook.write(fos);
//			
////			workbook.write(response.getOutputStream());
//			OutputStream output = response.getOutputStream();
//			BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
//			workbook.write(bufferedOutPut);
//			bufferedOutPut.flush();
//			bufferedOutPut.close();
//			output.close();
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//	}
	
}
